import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_li_ke_jie/core/utils/toast.dart';
import 'package:flutter_li_ke_jie/entity/app_user.dart';
import 'package:flutter_li_ke_jie/entity/base_response.dart';
import 'package:flutter_li_ke_jie/utils/common_util.dart';
import 'package:flutter_li_ke_jie/utils/log.dart';
import 'package:flutter_li_ke_jie/utils/sputil.dart';
import 'dart:io' show Platform;

import '../../constant/api_constant.dart';
import '../../core/http/http.dart';
import '../../router/router.dart';
import '../../utils/loading_utils.dart';
import '../../utils/nav_key.dart';
import '../../utils/navigator_util.dart';
import '../../utils/reg_util.dart';

///登录页面model
class LoginModel with ChangeNotifier{
  bool validatePhone = false;//手机号是否校验
  bool validateCode = false;//手机号是否校验
  bool hasLogin = false;//是否可以登录

  void checkPhone(String phone,String code){
    if(phone.length<11){
      validatePhone = false;
      hasLogin = false;
      notifyListeners();
    }else{
      //如果手机号不通过则为true
      validatePhone = !RegUtil.checkPhone(phone);
      //手机号校验过了。在判断是否可以登录
      if(!validatePhone){
          checkLogin(phone, code);
      }else{
        hasLogin = false;
      }
      notifyListeners();
    }
  }

  void checkCode(String phone,String code){
    if(CommonUtil.checkStrIsNull(code)){
      validateCode = true;
      hasLogin = false;
      notifyListeners();
    }else{
      validateCode = false;
      notifyListeners();
      checkLogin(phone, code);
    }

  }

  void checkLogin(String phone,String code){
    if(phone.length==11&&RegUtil.checkPhone(phone)&&!CommonUtil.checkStrIsNull(code)){
      hasLogin = true;
    }else{
      hasLogin = false;
    }
    notifyListeners();
  }


  //发送手机号码
  void sendCode(String phone){
    if(phone.length==11&&RegUtil.checkPhone(phone)){
      //发送验证码
      XHttp.post(SEND_CODE_API+"/"+phone).then((response){
        Log.e("发送验证码数据返回:$response");
        if(response!=null){
          ToastUtils.toast(response["msg"]);
        }
      });
    }else{
      validatePhone = true;//显示手机错误
      hasLogin = false;
      notifyListeners();
    }
  }
  
  //登录
  void login(String phone,String code){
    var map = <String,dynamic>{};
    map["phone"] = phone;
    map["code"] = code;
    // String param = json.encode(map);
    XHttp.postJson(LOGIN_API,map).then((response){
      Log.e("登录数据返回:$response");
      if(response["code"]==200){
        BaseResponse baseResponse = BaseResponse.fromJson(response);
        if(baseResponse!=null&&baseResponse.data!=null){
          AppUser appUser = AppUser.fromJson(baseResponse.data);
          if(appUser!=null&&appUser.token!=null){
            //保存sp用户数据
            var token = appUser.token;
            if(token!=null&&token.isNotEmpty){
              SPUtil.saveToken(token);
            }
            //保存渠道id
            SPUtil.saveChannelId("${appUser.channelId}");
            //保存用户id
            SPUtil.saveUserId("${appUser.userId}");
            //保存用户vip状态
            SPUtil.saveVipState(appUser.vipState);
            //判断认证状态
            String? authPhone = appUser.authPhone;
            String? cardId = appUser.cardId;
            String? name = appUser.name;
            if(authPhone!=null&&authPhone.isNotEmpty&&cardId!=null&&cardId.isNotEmpty&&name!=null&&name.isNotEmpty){
              SPUtil.saveAuthState("1");
            }else{
              SPUtil.saveAuthState("0");
            }
            //保存用户详情
            SPUtil.saveUserInfo(appUser);
            ToastUtils.toast("登录成功");
            //跳转登录
            Future.delayed(Duration(seconds:0)).then((onValue)  {
              BuildContext? context = NavKey.navKey.currentState?.overlay?.context;
              if(context!=null){
                NavigatorUtil.goAndFinish(context, HOME_PAGE);
              }
            });
            return;
          }
        }
        ToastUtils.toast("登录异常");
      }else{
        ToastUtils.error(response["msg"]);
      }
    });
  }

  //获取当前用户信息
  Future<bool> getUserInfo() async{
    String? userId = SPUtil.getUserId();
    if(userId!=null&&userId.isNotEmpty){
      //发送验证码
      return await XHttp.get(GET_USER_INFO+userId).then((response){
        Log.e("获取用户信息数据返回:$response");
        if(response!=null){
          if(response["data"]!=null){
            AppUser appUser = AppUser.fromJson(response["data"]);
            //更新缓存
            return SPUtil.saveUserInfo(appUser);
          }else{
            ToastUtils.toast(response["msg"]);
          }
        }
        return Future.value(true);
      });
    }
    return Future.value(true);
  }

}